'''
Created on Oct 1, 2009

@author: mkiyer
'''

import os
import sys
from veggie.app.chipseq.hpeak import HPeak
from veggie.app.chipseq.macs import MACS
from veggie.sample.sampledb2 import get_sampledb

def find_peaks(peakfinder, treatmentdict, controldict=None, cwd=None):
    # run peak finder on all combinations on treatments/controls
    for treatment_name, treatments in treatmentdict.iteritems():
        if controldict:
            for control_name, controls in controldict.iteritems():
                peakfinder.setUp(treatment_name, treatments, control_name, controls, cwd=cwd)
                peakfinder()
                peakfinder.tearDown()
        else:
            peakfinder.setUp(treatment_name, treatments, cwd=cwd)
            peakfinder()
            peakfinder.tearDown()

if __name__ == '__main__':
    
    args = [x for x in sys.argv[1:]]
    name = args[0]
    
    t_args = args[1].split(',')
    
    while len(t_args) > 0:
        
    t_flowcell = sys.argv[2]
    t_lane = sys.argv[3]
    t_dtype = sys.argv[4]
        
    
    
    name = sys.argv[1]
    t_name = '%s_treatment' % name
    c_name = '%s_control' % name    
    t_flowcell = sys.argv[2]
    t_lane = sys.argv[3]
    t_dtype = sys.argv[4]
    c_flowcell = sys.argv[5]
    c_lane = sys.argv[6]
    c_dtype = sys.argv[7]
    
    
    
    t_analysis = {t_name: []}
    for res in get_sampledb().get_analyses({'flowcell': t_flowcell,
                                            'lane_id': t_lane}):
        print 'treatment', res
        t_analysis[t_name].append(res.flowcell, (res.lane,), t_dtype)

    c_analysis = {c_name: []}
    for res in get_sampledb().get_analyses({'flowcell': c_flowcell,
                                            'lane_id': c_lane}):
        print 'control', res
        c_analysis[c_name] = (res.flowcell, (res.lane,), c_dtype)
    
    # default options
    hpeak_options = {'-fmin': 175,
                     '-fmax': 225,
                     '-sig': '1e-3',
                     '-wig': None,
                     '-ann': None}

    # create the app controller    
    hpeak_app = HPeak(options=hpeak_options)
    
    # run
    find_peaks(hpeak_app, t_analysis, c_analysis)